from django.views.generic.list_detail import object_list, object_detail
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.db.models import Q
from django.core.mail import send_mail
import pysvn
import difflib
from svndiffview import settings

def get_url():
    return settings.SVN_UTIL_REPO
    
def callback_ssl_server_trust_prompt( trust_data ):
    return True, trust_data['failures'], True

def get_login(realm, username, may_save):
    return true, settings.SVN_UTIL_USER, settings.SVN_UTIL_PASSWORD, true
    
def home(request):
    return HttpResponseRedirect("/home/")
    
def browse(request):
    revisions =  get_all_revision()
    return render_to_response('revisions.html',
                                      {"revisions":revisions},
                                      context_instance=RequestContext(request))
def diff(request, num_revision):
    diffs = genera_diff(num_revision)
    return render_to_response('diff.html',
                                      {"diffs":diffs},
                                      context_instance=RequestContext(request))

def get_changed_paths(num_revision):
    client = pysvn.Client()
    client.callback_get_login = get_login
    client.callback_ssl_server_trust_prompt = callback_ssl_server_trust_prompt 
    paths = []
    list_of_revprop_names =[]
    log_messages = client.log( get_url(),
        revision_start=pysvn.Revision(pysvn.opt_revision_kind.number, num_revision),
        revision_end=pysvn.Revision( pysvn.opt_revision_kind.number, num_revision),
        discover_changed_paths=True,
        strict_node_history=True,
        limit=0,
        peg_revision=pysvn.Revision( pysvn.opt_revision_kind.number, num_revision),
        include_merged_revisions=False,
        revprops=list_of_revprop_names )
    for x in log_messages:
        #for i in x['changed_paths']:
        #    print i['path']
        paths.append(x['changed_paths'])
    return paths

def genera_diff(num_revision):
    client = pysvn.Client()
    client.callback_get_login = get_login
    client.callback_ssl_server_trust_prompt = callback_ssl_server_trust_prompt 
    changes = get_changed_paths(int(num_revision))
    tables = []
    for groupChanges in changes:
        for change in groupChanges:
            path = get_url() + change['path']
            try:
                current_content = client.cat(path,
                    revision=pysvn.Revision(pysvn.opt_revision_kind.number,int(num_revision)),
                    peg_revision=pysvn.Revision(pysvn.opt_revision_kind.number,int(num_revision)))
            except pysvn.ClientError:
                current_content = ""

            try:
                previous_content = client.cat(path,
                                    revision=pysvn.Revision(pysvn.opt_revision_kind.number,int(num_revision)-1),
                                    peg_revision=pysvn.Revision(pysvn.opt_revision_kind.number,int(num_revision)-1))
            except pysvn.ClientError:
                previous_content = ""
            hd = difflib.HtmlDiff(4, 100)
            context_diff = []
            table = hd.make_table(previous_content.splitlines(),
                              current_content.splitlines(),
                              "Rev %s" % (str(int(num_revision)-1)),
                              "Rev %s" % (str(num_revision)),
                              context=context_diff)
            diff = diff_view()
            diff.html = table
            diff.path = path
            diff.action = change['action']
            tables.append(diff)
    return tables
    
def get_all_revision():
    client = pysvn.Client()
    client.callback_get_login = get_login
    client.callback_ssl_server_trust_prompt = callback_ssl_server_trust_prompt 
    c = client.revproplist( get_url(),
             revision=pysvn.Revision( pysvn.opt_revision_kind.head ) )
    num = c[0].number
    
    revisions = []
    rev_anterior = 0;
    if num-50 < 0:
        rev_anterior = 1
    else:
        rev_anterior = num-50
    for x in range(rev_anterior , num+1):
        rev = client.revproplist( get_url(),
            revision=pysvn.Revision(pysvn.opt_revision_kind.number,x))
        revision = Revision()
        revision.num = x
        revision.log = rev[1].get("svn:log")
        revision.author = rev[1].get("svn:author")
        revision.date =  rev[1].get("svn:date")
        revisions.append(revision)
    revisions.reverse()
    return revisions

class Revision:
    def __str__(self):
        return "%s " % ("revision")

class diff_view:
    def __str__(self):
        return "%s " % ("diff")